<?php

define(DEFAULT_MEM_CACHE_EXPIRY_TIME,0);

/**
 * Just for memcache
 *
 */
class ZendX_Cache_MemCache {
	/**
	 * Memcache object
	 *
	 * @var Memcache
	 */
	private static $cache;

	public static function getCache(){
		if (is_null(ZendX_Cache_MemCache::$cache)) {
			ZendX_Cache_MemCache::$cache = new Memcache;
			//由于看到打开关闭的链接太多, 试探着修改成持久链接
			$tmp = ZendX_Cache_MemCache::$cache->pconnect('localhost', '11211', 600);
			if($tmp){
				register_shutdown_function('ZendX_Cache_MemCache::close');
			}
		}
		return ZendX_Cache_MemCache::$cache;
	}
	
	public static function close(){
		if(ZendX_Cache_MemCache::$cache){
			ZendX_Cache_MemCache::$cache->close();
		}
	}

	public static function reset() {
		ZendX_Cache_MemCache::getCache()->flush();
		ZendX_Cache_Cache::reset();
	}

	public static function setValue($k, $v, $expired_time = DEFAULT_MEM_CACHE_EXPIRY_TIME, $compress = false) {
		$k = ZendX_Cache_MemCache::normalizeKey($k);
		$rs = ZendX_Cache_MemCache::getCache()->set($k, $v, false, $expired_time);
		//add request cache
		ZendX_Cache_Cache::setValue($k, $v);
		if (!$rs) {
			if(is_string($v)){
				$len = strlen($v);
			}else{
				$len = strlen(serialize($v));
			}
		}
	}
	
	public static function normalizeKey($k){
		return strlen($k) > 250 ? md5($k) : $k;
	}

	//  public static function setValues($values) {
	//    Logger::log("Storing multiple values in the memcache", LOGGER_CACHE);
	//    foreach ($values as $k => $v) {
	//      ZendX_Cache_MemCache::setValue($k, $v);
	//    }
	//  }

	public static function getValue($k) {
		$k = ZendX_Cache_MemCache::normalizeKey($k);
		$tmp = ZendX_Cache_Cache::getValue($k);
		if(empty($tmp)){
			$tmp = ZendX_Cache_MemCache::getCache()->get($k);
			if($tmp){
				ZendX_Cache_Cache::setValue($k, $tmp);
			}
		}
		return $tmp;
	}

	//  public static function getValues($keys) {
	//    Logger::log("Retrieving multiple vales from the memcache", LOGGER_CACHE);
	//    //$tmpArr = array();
	//    //foreach ($keys as $k) {
	//    //	$tmpArr[] = ZendX_Cache_MemCache::getCache()->get($k);
	//    //}
	//    return ZendX_Cache_MemCache::getCache()->get($keys);
	//  }

	public static function removeValue($k) {
		$k = ZendX_Cache_MemCache::normalizeKey($k);
		ZendX_Cache_MemCache::getCache()->delete($k);
		ZendX_Cache_Cache::removeValue($k);
	}
	
	/**
	 * replace
	 * @param unknown_type $k
	 * @param unknown_type $v
	 */
	public static function replaceValue ($k, $v, $compress = false, $expired_time = DEFAULT_MEM_CACHE_EXPIRY_TIME){
		$k = ZendX_Cache_MemCache::normalizeKey($k);
		ZendX_Cache_MemCache::getCache()->replace($k, $v, $compress, $expired_time);
	}
}
/*
class MemcacheWrapper extends Memcache{
	function __destruct() {
		$this->close();
	}
}
*/
?>